import type { ChatMessage } from './index';
import { useUserInfo } from '/@/stores/userInfo';
import { Session } from '/@/utils/storage';

/**
 * Process a message to extract any thought content enclosed in <think> tags
 * and update the message object accordingly
 */
export function withMessageThought(message: ChatMessage, startTime?: number) {
	const content = message.content;

	// If message already has reasoning_content, calculate thinking time
	if (message.reasoning_content) {
		const thinkingTime = startTime ? ((Date.now() - startTime) / 1000).toFixed(1) : '0.5';
		message.thinking_time = thinkingTime;
		// @ts-ignore - Add isThinking flag
		message.isThinking = false;
		return message;
	}

	const thinkPattern = /<think>(.*?)<\/think>/s;
	const matches = content.match(thinkPattern);

	if (matches) {
		const reasoning_content = matches[1].trim();
		const remainingContent = content.replace(thinkPattern, '').trim();
		message.content = remainingContent;

		if (reasoning_content) {
			// Calculate thinking time
			const thinkingTime = startTime ? ((Date.now() - startTime) / 1000).toFixed(1) : '0.5';

			// @ts-ignore - Add reasoning properties
			message.reasoning_content = reasoning_content;
			message.thinking_time = thinkingTime;
			// @ts-ignore - Add isThinking flag
			message.isThinking = true;
			return message;
		}
	}

	return message;
}

/**
 * 从会话存储中获取访问令牌
 * @returns {string} 访问令牌
 */
const token = computed(() => {
	return Session.getToken();
});

/**
 * 生成会话存储的key
 * @param {string} knowledgeId - 知识库ID
 * @param {boolean} notime - 是否不包含时间戳
 * @param {string} mcpId - MCP服务ID（可选）
 * @param {string} dataId - 数据ID（可选）
 * @returns {string} 会话存储key
 */
export const generateConversationKey = (knowledgeId: string, notime?: boolean, mcpId?: string, dataId?: string) => {
	// 构建基础key
	let key = `chat-${knowledgeId}-${useUserInfo().userInfos.user.userId}-${token.value}`;
	
	// 如果有mcpId，添加到key中
	if (mcpId) {
		key += `-mcp-${mcpId}`;
	}
	
	// 如果有dataId，添加到key中
	if (dataId) {
		key += `-data-${dataId}`;
	}
	
	// 如果需要时间戳，添加到key末尾
	if (!notime) {
		key += `-${Date.now()}`;
	}
	
	return key;
};
